<template>
  <div class="upload-dialog-modal" v-if="show" @click.self="close">
    <div class="upload-dialog" @click.stop>
      <div class="dialog-header">
        <h3>📎 上传课件</h3>
        <button class="close-btn" @click="close">×</button>
      </div>
      
      <div class="dialog-content">
        <div class="upload-area"
             @drop="handleDrop"
             @dragover="handleDragOver"
             @dragleave="handleDragLeave"
             :class="{ 'drag-over': isDragOver }"
             @click="triggerFileInput">
          <div class="upload-content">
            <i class="upload-icon">📁</i>
            <h4>拖拽文件到此处或点击上传</h4>
            <p>支持多种文件格式（PDF、PPT、Word、图片等）</p>
            <p class="file-size-hint">最大文件大小: {{ maxFileSizeMB }}MB</p>
            <input
              type="file"
              ref="fileInput"
              @change="handleFileSelect"
              style="display: none"
              :accept="acceptedTypes"
            />
          </div>
        </div>
        
        <!-- 文件列表 -->
        <div class="file-list" v-if="selectedFile">
          <div class="file-item">
            <div class="file-info">
              <div class="file-icon">📄</div>
              <div class="file-details">
                <div class="file-name">{{ selectedFile.name }}</div>
                <div class="file-size">{{ formatFileSize(selectedFile.size) }}</div>
              </div>
            </div>
            <button class="btn-remove" @click="removeFile">×</button>
          </div>
        </div>
        
        <!-- 上传进度 -->
        <div v-if="uploading" class="upload-progress">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: uploadProgress + '%' }"></div>
          </div>
          <div class="progress-text">上传中: {{ uploadProgress.toFixed(1) }}%</div>
        </div>
        
        <!-- 错误提示 -->
        <div v-if="error" class="error-message">
          {{ error }}
        </div>
      </div>
      
      <div class="dialog-footer">
        <button class="btn-cancel" @click="close">取消</button>
        <button 
          class="btn-confirm" 
          @click="confirm"
          :disabled="!selectedFile || uploading"
        >
          {{ uploading ? '上传中...' : '确认插入' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { childEnglishApi } from '@/api/childEnglishApi';

export default {
  name: 'CoursewareUploadDialog',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    maxFileSizeMB: {
      type: Number,
      default: 100
    }
  },
  data() {
    return {
      selectedFile: null,
      isDragOver: false,
      uploading: false,
      uploadProgress: 0,
      error: null,
      acceptedTypes: '.pdf,.ppt,.pptx,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.gif,.mp4,.mp3,.zip,.rar'
    };
  },
  methods: {
    triggerFileInput() {
      this.$refs.fileInput.click();
    },
    
    handleFileSelect(event) {
      const file = event.target.files[0];
      if (file) {
        this.validateAndSetFile(file);
      }
    },
    
    handleDragOver(event) {
      event.preventDefault();
      this.isDragOver = true;
    },
    
    handleDragLeave(event) {
      event.preventDefault();
      this.isDragOver = false;
    },
    
    handleDrop(event) {
      event.preventDefault();
      this.isDragOver = false;
      
      const files = event.dataTransfer.files;
      if (files.length > 0) {
        this.validateAndSetFile(files[0]);
      }
    },
    
    validateAndSetFile(file) {
      this.error = null;
      
      // 检查文件大小
      const maxSize = this.maxFileSizeMB * 1024 * 1024;
      if (file.size > maxSize) {
        this.error = `文件大小超过限制（最大 ${this.maxFileSizeMB}MB）`;
        return;
      }
      
      // 检查文件类型（可选，这里只做基本检查）
      const fileName = file.name.toLowerCase();
      const validExtensions = this.acceptedTypes.split(',').map(ext => ext.trim().substring(1));
      const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
      
      if (!validExtensions.includes(fileExtension)) {
        this.error = '不支持的文件类型，请上传支持的文件格式';
        return;
      }
      
      this.selectedFile = file;
    },
    
    removeFile() {
      this.selectedFile = null;
      this.error = null;
      if (this.$refs.fileInput) {
        this.$refs.fileInput.value = '';
      }
    },
    
    async confirm() {
      if (!this.selectedFile) {
        return;
      }
      
      try {
        this.uploading = true;
        this.uploadProgress = 0;
        this.error = null;
        
        // 使用文件上传API
        const response = await this.uploadFile(this.selectedFile);
        
        if (response && response.code === 200) {
          // 触发插入事件，传递文件URL和相关信息
          this.$emit('insert', {
            url: response.data.url || response.data.fileUrl || response.data.downloadUrl,
            fileName: this.selectedFile.name,
            fileSize: this.selectedFile.size,
            fileType: this.selectedFile.type
          });
          
          this.close();
        } else {
          this.error = response?.message || '上传失败，请重试';
        }
      } catch (error) {
        this.error = '上传失败: ' + (error.message || '未知错误');
        console.error('文件上传失败:', error);
      } finally {
        this.uploading = false;
      }
    },
    
    async uploadFile(file) {
      try {
        // 先尝试使用现有的文件上传API
        const response = await childEnglishApi.uploadFile(file, (progressEvent) => {
          if (progressEvent.total) {
            this.uploadProgress = (progressEvent.loaded / progressEvent.total) * 100;
          }
        });
        
        // 如果返回的是文件信息，需要转换为指导接口的格式
        if (response && response.code === 200 && response.data) {
          // 构建文件访问URL
          const fileUrl = `/file/download/${response.data.fileName}`;
          return {
            code: 200,
            data: {
              url: fileUrl,
              fileUrl: fileUrl,
              downloadUrl: fileUrl,
              fileName: response.data.fileName || response.data.originalName,
              size: response.data.size,
              contentType: response.data.contentType
            }
          };
        }
        
        return response;
      } catch (error) {
        // 如果使用childEnglishApi失败，尝试直接使用axios调用指导接口
        const axios = (await import('axios')).default;
        const token = sessionStorage.getItem('token');
        const csrfToken = localStorage.getItem('csrfToken');
        const formData = new FormData();
        formData.append('file', file);
        
        // 构建请求头
        const headers = {
          'Content-Type': 'multipart/form-data'
        };
        
        if (token) {
          headers['Authorization'] = `Bearer ${token}`;
        }
        
        if (csrfToken) {
          headers['X-CSRF-TOKEN'] = csrfToken;
        }
        
        const response = await axios.post(
          `${childEnglishApi.getCurrentServer()}/api/guidance/upload-courseware`,
          formData,
          {
            headers: headers,
            withCredentials: true, // 重要：支持CORS和Session
            timeout: 120000, // 120秒超时，大文件上传需要更长时间
            onUploadProgress: (progressEvent) => {
              if (progressEvent.total) {
                this.uploadProgress = (progressEvent.loaded / progressEvent.total) * 100;
              }
            }
          }
        );
        
        // 从响应头获取CSRF Token
        const newCsrfToken = response.headers['x-csrf-token'];
        if (newCsrfToken) {
          localStorage.setItem('csrfToken', newCsrfToken);
        }
        
        return response.data;
      }
    },
    
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
    },
    
    close() {
      this.$emit('close');
      // 重置状态
      this.selectedFile = null;
      this.error = null;
      this.uploading = false;
      this.uploadProgress = 0;
      this.isDragOver = false;
      if (this.$refs.fileInput) {
        this.$refs.fileInput.value = '';
      }
    }
  }
};
</script>

<style scoped>
.upload-dialog-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.upload-dialog {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.dialog-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 28px;
  color: #7f8c8d;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  line-height: 30px;
  transition: color 0.3s;
}

.close-btn:hover {
  color: #e74c3c;
}

.dialog-content {
  padding: 20px;
}

.upload-area {
  border: 2px dashed #bdc3c7;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 20px;
}

.upload-area:hover {
  border-color: #3498db;
  background: #f8f9fa;
}

.upload-area.drag-over {
  border-color: #3498db;
  background: #e8f4f8;
}

.upload-content {
  pointer-events: none;
}

.upload-icon {
  font-size: 48px;
  display: block;
  margin-bottom: 10px;
}

.upload-content h4 {
  margin: 10px 0;
  color: #2c3e50;
}

.upload-content p {
  margin: 5px 0;
  color: #7f8c8d;
  font-size: 14px;
}

.file-size-hint {
  font-size: 12px;
  color: #95a5a6;
}

.file-list {
  margin-bottom: 20px;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 15px;
  flex: 1;
}

.file-icon {
  font-size: 32px;
}

.file-details {
  flex: 1;
}

.file-name {
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 5px;
  word-break: break-all;
}

.file-size {
  font-size: 14px;
  color: #7f8c8d;
}

.btn-remove {
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  font-size: 20px;
  cursor: pointer;
  transition: all 0.3s;
  flex-shrink: 0;
}

.btn-remove:hover {
  background: #c0392b;
  transform: scale(1.1);
}

.upload-progress {
  margin-bottom: 10px;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: #ecf0f1;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 5px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #3498db, #2ecc71);
  transition: width 0.3s;
}

.progress-text {
  text-align: center;
  font-size: 12px;
  color: #7f8c8d;
}

.error-message {
  background: #fee;
  color: #c33;
  padding: 10px;
  border-radius: 6px;
  margin-bottom: 10px;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #e0e0e0;
}

.btn-cancel,
.btn-confirm {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-cancel {
  background: #ecf0f1;
  color: #2c3e50;
}

.btn-cancel:hover {
  background: #bdc3c7;
}

.btn-confirm {
  background: #3498db;
  color: white;
}

.btn-confirm:hover:not(:disabled) {
  background: #2980b9;
}

.btn-confirm:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}
</style>

